//
//  HomePictureView.swift
//  我的微博
//
//  Created by shmily on 15/8/2.
//  Copyright © 2015年 Stanford-IOS8-Swift-shmilyAshen. All rights reserved.
//

import UIKit
import SDWebImage
/// 通知的名称
let kNotificationDidSelectItem = "notificationDidSelectItem"
///  通知传递的 url
let kNotificationDidSelectUrls = "kNotificationDidSelectUrls"
/// 通知传递的当前点击的 cell
let kNotificationDidSelectIndex = "kNotificationDidSelectIndex"
class HomePictureView: UICollectionView {
    
    //MARK:- 属性
    //数据模型
    var status: BlogContent?{
        didSet {
            pictureNumber = status?.picUrls?.count
            sizeToFit()
            //刷新数据
            reloadData()
        }
    }
    /// 图片的数量
    private var pictureNumber: Int?
    
    /// 设置图片的小宽度
    private let pictureMinWidth = 90
    /// 设置图片的大宽度
    private let pictureMaxWidth = 150
    /// 屏幕宽度
    private let screenWidth = UIScreen.mainScreen().bounds.width
    /// 可重用 id
    private let reuserID = "pictureViewID"
    
    //MARK:- 方法
    /// 计算视图的尺寸
    private func calcViewLayout() ->CGSize{
        //0张图像
        if pictureNumber == nil {
            return CGSizeZero
        }
        //1张图像
        if pictureNumber == 1 {
            let key = status!.picUrls![0].absoluteString
            let img = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            var size = CGSize(width: 150, height: 120)
            if img != nil {
                size = img.size
            }
            //防止尺寸过大或过小
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width > UIScreen.mainScreen().bounds.width ? 250 : size.width
            flowLayout.itemSize = size
            
            return size
        }
        //4张图像
        if pictureNumber == 4 {
            flowLayout.itemSize = CGSize(width: pictureMinWidth, height: pictureMinWidth)
             let width = pictureMinWidth * 2 + Int(homeTopViewMargin)
            let height = width
            flowLayout.itemSize = CGSize(width: pictureMinWidth, height: pictureMinWidth)
            return CGSize(width: width, height: height)
        }
        //其它类型
        let rowCount = (pictureNumber! - 1 ) / 3 + 1
        flowLayout.itemSize = CGSize(width: pictureMinWidth, height: pictureMinWidth)
        let width = CGFloat(pictureMinWidth * 3) + homeTopViewMargin * (3 - 1)
        let height = CGFloat(pictureMinWidth * rowCount) + homeTopViewMargin * CGFloat(rowCount - 1)
        return CGSize(width: width, height: height)
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewLayout()
    }
    private let flowLayout: UICollectionViewFlowLayout = {
        let flow = UICollectionViewFlowLayout()
        flow.minimumInteritemSpacing = CGFloat(homeTopViewMargin)
        flow.minimumLineSpacing = CGFloat(homeTopViewMargin)
        return flow
    }()
    
    /// 计算当前的 cell 的 frame 值
    func pictureFrame(indexPath: NSIndexPath) ->CGRect {
        let cell = cellForItemAtIndexPath(indexPath) as! PictureViewCell // 获取 cell
        let rect = convertRect(cell.frame, fromCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        print(rect)
        return rect
    }
    
    //MARK:- 初始化函数
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)
        //设置数据源为其本身
        self.dataSource = self
        self.delegate = self
        backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        registerClass(PictureViewCell.self, forCellWithReuseIdentifier: reuserID)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

//MARK:- 数据源可代理方法
extension HomePictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureNumber ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuserID, forIndexPath: indexPath) as! PictureViewCell
        //设置 cell 的数据
        cell.pictureUrl = status?.picUrls![indexPath.item]
        
        return cell
    }
    
    // 单击后将图片和 indexPath 传递给图片浏览器
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //发送通知,HomeVC监听后,创建图片浏览器
        let urls = status?.largePicUrls
        NSNotificationCenter.defaultCenter().postNotificationName(kNotificationDidSelectItem, object: self, userInfo: [kNotificationDidSelectUrls:urls!,kNotificationDidSelectIndex:indexPath.item])
        
        //计算当前 cell的 frame
        let img = UIImageView(frame: pictureFrame(indexPath))
        img.backgroundColor = UIColor.redColor()
        UIApplication.sharedApplication().keyWindow?.addSubview(img)
    }
}

//MARK:- 自定义 collectionViewCell
/// pictureView 的 cell 类
class PictureViewCell: UICollectionViewCell {
    /// 传递数据方法
    private var pictureUrl: NSURL?{
        didSet {
            picture.sd_setImageWithURL(pictureUrl!)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //设置 cell 的内容
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpUI(){
        contentView.addSubview(picture)
        //设置布局
        picture.ff_Fill(contentView)
    }
    /// 懒加载 cell 的视图
    private lazy var picture: UIImageView = {
        let img = UIImageView()
        img.contentMode = UIViewContentMode.ScaleAspectFill
        img.clipsToBounds = true
        return img
    }()
    
}
